<?php

namespace App\Models;

class User extends Base
{

    /**
     * @param $data
     * @param $errors
     * @return bool
     */
    public function validInput($data, $authitem, &$errors)
    {
        $ret = [];
        foreach ($authitem['base'] as $item) {
            $ret[] = (string) $item['item_field'];
        }
        foreach ($authitem['club'] as $item) {
            $ret[] = (string) $item['item_field'];
        }
        $config = [];
        if (in_array('username', $ret)) {
            unset($authitem['base']['username']);
            $config['username'] = array(
                array('isNull', 'username_not_null'),
            );
        }
        if (in_array('realname', $ret)) {
            unset($authitem['base']['realname']);
            $config['realname'] = array(
                array('isNull', 'realname_not_null'),
            );
        }
        if (in_array('birthday', $ret)) {
            unset($authitem['base']['birthday']);
            $config['birthday'] = array(
                array('isNull', 'birthday_not_null'),
            );
        }
        if (in_array('mobile', $ret)) {
            unset($authitem['base']['mobile']);
            $config['mobile'] = array(
                array('isNull', 'mobile_not_null'),
                array('isMobile', 'mobile_error'),
            );
        }
        if (in_array('address', $ret)) {
            unset($authitem['base']['address']);
            $config['address'] = array(
                array('isNull', 'address_not_null'),
            );
        }
        if (in_array('industry', $ret)) {
            unset($authitem['base']['industry']);
            $config['industry'] = array(
                array('isNull', 'industry_not_null'),
            );
        }
        if (in_array('summary', $ret)) {
            unset($authitem['base']['summary']);
            $config['summary'] = array(
                array('isNull', 'summary_not_null'),
            );
        }
        foreach($authitem['base'] as $item){
            $config[$item['item_field']] = [
                ['isNull', $item['item_name'] . '不能为空',]
            ];
        }
        $validator = new \App\Extend\Validator($this->container);
        if (!$result = $validator->validate($config, $data)) {
            $errors = $validator->error;
            $this->language->validator('user', $errors);
        }

        return $result;
    }

    /**
     * 用户认证信息
     * @param int $clubUserId 车友会用户ID
     * @return array
     */
    public function userAuthInfo($clubUserId = 0)
    {
        $authModel = $this->container->model('Authitem');
        $authitem = $authModel->getAuthitem($this->club['id']);
        //基础认证信息
        $sql = "select * from tb_club_user where deleted = 0 and id = ?";
        $baseAuth = $this->fetchOne($sql, [$clubUserId]);
        $baseAuth['other'] = json_decode($baseAuth['other'], true);
        $baseAuth['other'] = is_array($baseAuth['other']) ? $baseAuth['other'] : [];
        $baseAuth = array_merge($baseAuth, $baseAuth['other']);
        //车友会认证信息
        $clubAuth = $this->get('tb_club_user_authinfo', 'authinfo', ['deleted' => 0, 'club_user_id' => $clubUserId]);
        $clubAuth && ($clubAuth = json_decode($clubAuth['authinfo'], true));
        return $this->centenAssambleAuthInfo($baseAuth, $clubAuth);
    }

    /**
     * 根据认证设置组装认证信息
     * @param array $baseAuth 基础认证信息
     * @param array $clubAuth 车友会认证信息
     * @return array
     */
    public function assambleAuthInfo($baseAuth, $clubAuth)
    {
        $authModel = $this->container->model('Authitem');
        $authitem = $authModel->getAuthitem($this->club['id']);

        $ret = [];
        foreach ($authitem['base'] as $item) {
            $ret['base'][$item['item_field']] = (string) $baseAuth[$item['item_field']];
        }
        foreach ($authitem['club'] as $item) {
            $ret['club'][$item['item_field']] = (string) $clubAuth[$item['item_field']];
        }
        return $ret;
    }

    public function centenAssambleAuthInfo($baseAuth, $wechaAuth)
    {
        $authModel = $this->container->model('Authitem');
        $authitem = $authModel->getAuthitem($this->club['id']);
        $ret = [];
        foreach ($authitem['base'] as $item) {
            $temp['item_field'] = (string) $item['item_field'];
            $temp['item_name'] = (string) $item['item_name'];
            $temp['item_val'] = (string) $baseAuth[$item['item_field']];
            $ret['base'][] = $temp;
        }
        foreach ($authitem['club'] as $item) {
            $temp['item_field'] = (string) $item['item_field'];
            $temp['item_name'] = (string) $item['item_name'];
            $temp['item_val'] = (string) $wechaAuth[$item['item_field']];
            $ret['club'][] = $temp;
        }
        return $ret;
    }

    public function getUserByMobile($mobile = '')
    {
        $sql = "select cu.*,wu.headimgurl,c.club_name,c.logo from tb_club_user cu
                inner join tb_club c on c.id = cu.club_id and c.deleted = 0
                left join tb_wechat_user wu on wu.club_user_id = cu.id and wu.deleted = 0
                where cu.mobile = '{$mobile}' and cu.club_id = {$this->club['id']} and cu.deleted = 0";
        $one = $this->fetchOne($sql);
        if (!$one) {
            return false;
        }
        return $one;
    }

    /**
     * 车友会用户列表
     * @param array $sh
     * @return array
     */
    public function clubUserList($sh = [])
    {
        $curpage = $sh['page'];
        $perpage = isset($sh['perpage']) ? $sh['perpage'] : 20;
        $sql = "select cu.*,wu.headimgurl from tb_club_user cu
                left join tb_wechat_user wu on wu.club_user_id = cu.id and wu.deleted = 0
                where cu.deleted = 0";
        $cond = [
            'cu.club_id' => $sh['club_id']
        ];
        if ($sh['auth_status']) {
            $cond['cu.auth_status'] = $sh['auth_status'];
        }
        $params = $this->cond($sql, $cond);
        $this->orderBy($sql, 'b.desc', $this->codeConfig['order']['user']);
        $list = $this->paginate($sql, $curpage, $perpage, $params);
        return $list;
    }

    /**
     * 保存用户认证信息
     * @param array $auth
     * @return boolean
     */
    public function saveAuth(&$data)
    {
        $clubUser = $this->get('tb_club_user', 'auth_status', ['deleted' => 0, 'mobile' => $data['mobile'], 'club_id' => $this->club['id']]);
        if ($clubUser && ($clubUser['auth_status'] == 1 || $clubUser['auth_status'] == 2)) {
            return false;
        }
        $authModel = $this->container->model('Authitem');
        $authitem = $authModel->getAuthitem($this->club['id']);

        $authInfo = $this->assambleAuthInfo($data, $data);
        $baseAuth = $authInfo['base'];
        $clubAuth = $authInfo['club'];

        $this->begin();

        //平台用户
        $globalUser = $this->get('tb_global_user', 'id', ['deleted' => 0, 'mobile' => $baseAuth['mobile']]);
        $globalUserId = $globalUser['id'];

        $baseData = [];
        foreach ($baseAuth as $k => $v) {
            if (in_array($k, $this->codeConfig['baseField'])) {
                $baseData[$k] = $v;
            } else {
                $baseData['other'][$k] = $v;
            }
        }
        $baseData['other'] = json_encode($baseData['other']);

        if (!$globalUserId) {
            $baseAuth['created'] = NOW;
            $globalUserId = $this->insert('tb_global_user', $baseData);
            if ($globalUserId === false) {
                $this->rollback();
                return false;
            }
        }

        //车友会用户
        $clubUser = $this->get('tb_club_user', 'id', ['deleted' => 0, 'mobile' => $baseAuth['mobile'], 'club_id' => $this->club['id']]);
        $clubUserId = $clubUser['id'];
        if (!$clubUserId) {
            $baseData['created'] = NOW;
            $baseData['global_user_id'] = $globalUserId;
            $baseData['club_id'] = $this->club['id'];
            $clubUserId = $this->insert('tb_club_user', $baseData);
            if ($clubUserId === false) {
                $this->rollback();
                return false;
            }
        } else {
            if ($this->update('tb_club_user', $baseData, ['id' => $clubUserId]) === false) {
                $this->rollback();
                return false;
            }
        }
        $refererId = $_COOKIE['referer_id_' . $this->club['id']];
        $clubUserUpdate = [
            'auth_status' => 1,
            'global_user_id' => $globalUserId,
            'referer_id' => $refererId ?: 0
        ];
        if ($this->update('tb_club_user', $clubUserUpdate, ['id' => $clubUserId]) === false) {
            $this->rollback();
            return false;
        }
        $applyCond = [
            'club_id' => $this->club['id'],
            'club_user_id' => $clubUserId
        ];
        $apply = $this->get('tb_club_user_auth_apply', '*', $applyCond);
        if (!$apply) {
            $applyCond['created'] = NOW;
            $applyCond['auth_status'] = 1;
            if ($this->insert('tb_club_user_auth_apply', $applyCond) === false) {
                $this->rollback();
                return false;
            }
        } else {
            if ($this->update('tb_club_user_auth_apply', ['auth_status' => 1], $applyCond) === false) {
                $this->rollback();
                return false;
            }
        }
        $authinfo = [
            'club_id' => $this->club['id'],
            'authinfo' => json_encode($clubAuth),
            'club_user_id' => $clubUserId,
            'created' => NOW,
        ];
        if ($this->replace('tb_club_user_authinfo', $authinfo) === false) {
            $this->rollback();
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * 下拉数据组装
     * @param $authitem
     */
    public function authitem(&$authitem)
    {
        foreach ($authitem as &$val) {
            array_walk($val, function (&$item) {
                if ($item['item_type'] == 4) {
                    $item['item_val_list'] = explode(',', $item['item_val']);
                }
            });
        }
        return $authitem;
    }

    /**
     * 认证状态修改
     * @param array $data
     * @param $data
     * @return bool
     */
    public function changeStatus($data, &$error)
    {
        if (!$data['id'] || !$data['status']) {
            $error = 'param_error';
            return false;
        }
        $cond = [
            'deleted' => 0,
            'club_user_id' => $data['id']
        ];
        $apply = $this->get('tb_club_user_auth_apply', '*', $cond);
        if (!$apply) {
            $error = 'apply_not_found';
            return false;
        }
        if ($apply['auth_status'] == 2) {
            $error = 'apply_already_succ';
            return false;
        }
        if ($apply['auth_status'] == 3) {
            $error = 'apply_already_deny';
            return false;
        }
        $this->begin();
        if ($this->update('tb_club_user_auth_apply', ['auth_status' => $data['status']], $cond) === false) {
            $this->rollback();
            return false;
        }
        if ($this->update('tb_club_user', ['auth_status' => $data['status']], ['id' => $data['id']]) === false) {
            $this->rollback();
            return false;
        }
        if ($data['status'] == 2) {
            $point = [
                'club_user_id' => $data['id'],
                'point' => $this->codeConfig['pointValue'][1]['point'],
                'source' => 1,
                'created' => NOW
            ];
            if ($this->insert('tb_club_user_point', $point) === false) {
                $this->rollback();
                return false;
            }
            $sql = "update tb_club_user set point = point + {$this->codeConfig['pointValue'][1]['point']}
                    where id = {$data['id']}";
            if (!$this->exec($sql)) {
                $this->rollback();
                return false;
            }
        }
        $this->commit();
        return true;
    }

    public function validMobile($data, &$errors)
    {
        $config = [
            'mobile' => [
                ['isNull', 'phone_not_null'],
                ['isMobile', 'phone_error'],
            ],
            'code' => [
                ['isNull', 'code_not_null'],
                ['checkCode', 'code_error', ['mobile' => $data['mobile']]],
            ],
        ];
        $validator = new \App\Extend\Validator($this->container);
        if (!$result = $validator->validate($config, $data)) {
            $errors = $validator->error;
            $this->language->validator('user', $errors);
        }
        return $result;
    }

}
